﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Text;
using System.Threading.Tasks;
using SystemUpdatesCore.Files;

namespace SystemUpdatesCore.Client
{
    public class ClientFile : IClient
    {
        public ClientFile() : base()
        {
            fileSave = new FileSave();
        }

        FileSave fileSave;

        /// <summary>
        /// 客户端存储配置
        /// </summary>
        public ClientUrlMode ClientUrl { get; set; }

        /// <summary>
        /// 获取本地版本信息，如果未获取到返回null
        /// </summary>
        /// <param name="clienUrl"></param>
        /// <returns></returns>
        public async Task<ClientVersionModel> GetVersion(ClientUrlMode clientUrl)
        {
            ClientVersionModel ver = null;

            //从指定配置中获取本地版本信息
            if (File.Exists(clientUrl.Url))
            {
                ver = await fileSave.Read<ClientVersionModel>(clientUrl.Url);
                if (ver != null)
                {
                    return ver;
                }
            }

            //从默认位置中获取本地版信息
            string path = Path.Combine(fileSave.FilePath, clientUrl.Url);
            if (File.Exists(path))
            {
                ver = await fileSave.Read<ClientVersionModel>(path);
                if (ver != null)
                {
                    return ver;
                }
            }

            return ver;
        }

        /// <summary>
        /// 保存新版本到本地
        /// </summary>
        /// <param name="clienUrl"></param>
        /// <param name="clientVersion"></param>
        /// <returns></returns>
        public async Task SaveVersion(ClientUrlMode clientUrl, ClientVersionModel clientVersion)
        {
            //写入到指定配置中
            if (File.Exists(clientUrl.Url))
            {
                await fileSave.Write(clientVersion, clientUrl.Url);
            }

            string path = Path.Combine(fileSave.FilePath, clientUrl.Url);
            //写入到默认位置
            //if (File.Exists(path))
            //{
                await fileSave.Write(clientVersion, path);
            //}

        }
    }
}
